const express = require('express');
const router = express.Router();
const { authenticateToken } = require('./auth');
const db = require('../database/connection');

// Get user dashboard data
router.get('/dashboard', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;

    // Get user dashboard data from view
    const dashboardData = await db.query(
      'SELECT * FROM user_dashboard WHERE id = ?',
      [userId]
    );

    if (dashboardData.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    const userData = dashboardData[0];

    // Get recent transactions
    const recentTransactions = await db.query(
      `SELECT transaction_type, amount, status, created_at
       FROM transactions
       WHERE user_id = ?
       ORDER BY created_at DESC
       LIMIT 10`,
      [userId]
    );

    // Get staking summary
    const stakingSummary = await db.query(
      `SELECT
         COUNT(*) as active_stakes,
         SUM(amount) as total_staked,
         MIN(staking_date) as first_stake_date
       FROM staking_records
       WHERE user_id = ? AND status = 'active'`,
      [userId]
    );

    // Get referral stats
    const referralStats = await db.query(
      `SELECT
         COUNT(DISTINCT r.id) as total_referrals,
         COALESCE(SUM(rr.reward_amount), 0) as total_referral_rewards
       FROM users u
       LEFT JOIN users r ON u.referral_code = r.referred_by
       LEFT JOIN referral_rewards rr ON u.id = rr.referrer_id
       WHERE u.id = ?`,
      [userId]
    );

    res.json({
      user: userData,
      recentTransactions,
      staking: stakingSummary[0] || { active_stakes: 0, total_staked: 0, first_stake_date: null },
      referrals: referralStats[0] || { total_referrals: 0, total_referral_rewards: 0 }
    });

  } catch (error) {
    console.error('Dashboard error:', error);
    res.status(500).json({ error: 'Failed to fetch dashboard data' });
  }
});

// Get user balance
router.get('/balance', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;

    const balance = await db.query(
      'SELECT available_balance, staked_balance, total_earned FROM user_balances WHERE user_id = ?',
      [userId]
    );

    if (balance.length === 0) {
      return res.status(404).json({ error: 'User balance not found' });
    }

    res.json(balance[0]);

  } catch (error) {
    console.error('Balance error:', error);
    res.status(500).json({ error: 'Failed to fetch balance' });
  }
});

// Get user profile
router.get('/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;

    const user = await db.query(
      `SELECT id, wallet_address, referral_code, referred_by, created_at
       FROM users
       WHERE id = ?`,
      [userId]
    );

    if (user.length === 0) {
      return res.status(404).json({ error: 'User not found' });
    }

    res.json(user[0]);

  } catch (error) {
    console.error('Profile error:', error);
    res.status(500).json({ error: 'Failed to fetch profile' });
  }
});

// Update user profile
router.put('/profile', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;
    const { email } = req.body;

    if (email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email)) {
      return res.status(400).json({ error: 'Invalid email format' });
    }

    // Check if email is already taken by another user
    if (email) {
      const existingEmail = await db.query(
        'SELECT id FROM users WHERE email = ? AND id != ?',
        [email, userId]
      );

      if (existingEmail.length > 0) {
        return res.status(409).json({ error: 'Email already taken' });
      }
    }

    await db.query(
      'UPDATE users SET email = ? WHERE id = ?',
      [email, userId]
    );

    res.json({ message: 'Profile updated successfully' });

  } catch (error) {
    console.error('Profile update error:', error);
    res.status(500).json({ error: 'Failed to update profile' });
  }
});

// Get user transaction history
router.get('/transactions', authenticateToken, async (req, res) => {
  try {
    const userId = req.user.userId;
    const { page = 1, limit = 20, type } = req.query;
    const offset = (page - 1) * limit;

    let whereClause = 'WHERE user_id = ?';
    const params = [userId];

    if (type) {
      whereClause += ' AND transaction_type = ?';
      params.push(type);
    }

    const transactions = await db.query(
      `SELECT transaction_hash, transaction_type, amount, from_address, to_address,
              status, created_at, block_number
       FROM transactions
       ${whereClause}
       ORDER BY created_at DESC
       LIMIT ? OFFSET ?`,
      [...params, parseInt(limit), offset]
    );

    const totalResult = await db.query(
      `SELECT COUNT(*) as total FROM transactions ${whereClause}`,
      params
    );

    res.json({
      transactions,
      pagination: {
        page: parseInt(page),
        limit: parseInt(limit),
        total: totalResult[0].total,
        totalPages: Math.ceil(totalResult[0].total / limit)
      }
    });

  } catch (error) {
    console.error('Transaction history error:', error);
    res.status(500).json({ error: 'Failed to fetch transaction history' });
  }
});

module.exports = router;